<template>
  <div class="data-source-config">
    <button @click="closeConfig" class="close-button">X</button>
    <h2>数据源配置</h2>
    <!-- 数据源类型选择 -->
    <label for="dataSourceType">选择数据源类型:</label>
    <select id="dataSourceType" v-model="selectedDataSource">
      <option
        v-for="type in dataSourceTypes"
        :key="type.value"
        :value="type.value"
      >
        {{ type.label }}
      </option>
    </select>

    <!-- 数据库配置表单 -->
    <div v-if="selectedDataSource === 'database'" class="config-form">
      <h3>数据库配置</h3>
      <label
        >主机名:
        <input type="text" v-model="dbConfig.host" placeholder="请输入主机名" />
      </label>
      <label
        >端口:
        <input
          type="number"
          v-model="dbConfig.port"
          placeholder="请输入端口号"
        />
      </label>
      <label
        >用户名:
        <input
          type="text"
          v-model="dbConfig.username"
          placeholder="请输入用户名"
        />
      </label>
      <label
        >密码:
        <input
          type="password"
          v-model="dbConfig.password"
          placeholder="请输入密码"
        />
      </label>
      <label
        >数据库名称:
        <input
          type="text"
          v-model="dbConfig.database"
          placeholder="请输入数据库名称"
        />
      </label>
    </div>

    <!-- API 配置表单 -->
    <div v-else-if="selectedDataSource === 'api'" class="config-form">
      <h3>API 配置</h3>
      <label
        >URL:
        <input
          type="text"
          v-model="apiConfig.url"
          placeholder="请输入API地址"
        />
      </label>
      <label
        >请求方法:
        <select v-model="apiConfig.method">
          <option value="GET">GET</option>
          <option value="POST">POST</option>
        </select>
      </label>
      <label
        >认证方式:
        <select v-model="apiConfig.authType">
          <option value="none">无</option>
          <option value="basic">Basic Auth</option>
          <option value="token">Token</option>
        </select>
      </label>
      <div v-if="apiConfig.authType === 'basic'">
        <label
          >用户名:
          <input
            type="text"
            v-model="apiConfig.authUsername"
            placeholder="请输入用户名"
          />
        </label>
        <label
          >密码:
          <input
            type="password"
            v-model="apiConfig.authPassword"
            placeholder="请输入密码"
          />
        </label>
      </div>
      <div v-else-if="apiConfig.authType === 'token'">
        <label
          >Token:
          <input
            type="text"
            v-model="apiConfig.authToken"
            placeholder="请输入Token"
          />
        </label>
      </div>
    </div>

    <!-- 文件配置表单 -->
    <div v-else-if="selectedDataSource === 'file'" class="config-form">
      <h3>文件配置</h3>
      <label
        >文件类型:
        <select v-model="fileConfig.fileType">
          <option value="excel">Excel</option>
          <option value="csv">CSV</option>
          <option value="json">JSON</option>
        </select>
      </label>
      <label v-if="fileConfig.fileType !== 'excel'"
        >文件路径:
        <input
          type="text"
          v-model="fileConfig.filePath"
          placeholder="请输入文件路径"
        />
      </label>

      <!-- 新增上传Excel文件的输入框 -->
      <label v-if="fileConfig.fileType === 'excel'">
        上传Excel文件:
        <input type="file" @change="handleExcelUpload" accept=".xls,.xlsx" />
      </label>
    </div>

    <!-- 测试连接按钮 -->
    <button @click="testConnection">测试连接</button>

    <!-- 数据预览 -->
    <div v-if="previewData.length > 0" class="preview">
      <h3>数据预览</h3>
      <table>
        <thead>
          <tr>
            <th v-for="(value, key) in previewData[0]" :key="key">{{ key }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in previewData" :key="index">
            <td v-for="(value, key) in item" :key="key">{{ value }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>



<script setup>
import { defineEmits,ref } from "vue";
import * as XLSX from "xlsx";

// 定义 emit
const emit = defineEmits(["close"]);

// 关闭函数
function closeConfig() {
  emit("close");
}

// 其他 data 和方法可以直接写在这里
const dataSourceTypes = [
  { label: "数据库", value: "database" },
  { label: "API", value: "api" },
  { label: "文件", value: "file" },
];
const selectedDataSource = ref("");
const dbConfig = ref({
  host: "",
  port: "",
  username: "",
  password: "",
  database: "",
});
const apiConfig = ref({
  url: "",
  method: "GET",
  authType: "none",
  authUsername: "",
  authPassword: "",
  authToken: "",
});
const fileConfig = ref({
  filePath: "",
  fileType: "excel",
});
const previewData = ref([]);

function testConnection() {
  if (selectedDataSource.value === "database") {
    console.log("测试数据库连接:", dbConfig.value);
    previewData.value = [
      { id: 1, server_name: "ServerA", status: "正常" },
      { id: 2, server_name: "ServerB", status: "异常" },
    ];
  } else if (selectedDataSource.value === "api") {
    console.log("测试API连接:", apiConfig.value);
    previewData.value = [
      { id: 101, temperature: "25°C", location: "机房A" },
      { id: 102, temperature: "27°C", location: "机房B" },
    ];
  } else if (selectedDataSource.value === "file") {
    console.log("测试文件读取:", fileConfig.value);
    previewData.value = [
      { timestamp: "2023-10-01T12:00:00Z", usage: "85%" },
      { timestamp: "2023-10-01T13:00:00Z", usage: "90%" },
    ];
  }
}

function handleExcelUpload(event) {
  const file = event.target.files[0];
  if (file) {
    const reader = new FileReader();
    reader.onload = (e) => {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: "array" });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
      previewData.value = jsonData.slice(0, 5).map((row) => ({
        col0: row[0] || "",
        col1: row[1] || "",
        col2: row[2] || "",
      }));
    };
    reader.readAsArrayBuffer(file);
  }
}
</script>

<style scoped>
.data-source-config {
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  width: 400px;
  color: #fff;
  height: 55vh;
  overflow: scroll;
}
::-webkit-scrollbar {
  display: none;
}

label {
  display: block;
  margin-top: 10px;
}

input,
select {
  width: 100%;
  padding: 6px;
  margin-top: 4px;
}

.config-form {
  margin-top: 15px;
  border-top: 1px solid #eee;
  padding-top: 10px;
}

button {
  margin-top: 20px;
  padding: 10px 15px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.preview {
  margin-top: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th,
td {
  border: 1px solid #ddd;
  padding: 8px;
}

th {
  background-color: #f2f2f2;
}


.close-button {
  position: absolute;
  top: -10px;
  right: 10px;
  color: white;
  background-color: #cccccc00;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
  border-radius: 4px;
  font-size: 24px;

  &:hover {
    color: #a1a1a1;
  }
}
</style>
